﻿using System;
using System.Collections.Generic;
using System.Linq;
using Interfaces;
using PeopleEntity;
using PeopleException;

namespace PeopleBll
{
    public class PeoplesBll:IPeopleBll
    {
        private readonly IPeoplesDal _peoplesDal;

        public PeoplesBll(IPeoplesDal peoplesDal)
        {
            _peoplesDal = peoplesDal;
        }

        public bool Create(string name, DateTime dateBirth, float weight, float height )
        {
            var result = false;
            try
            {
                var people = new PeopleBase(name, dateBirth, weight, height);
                result=_peoplesDal.Create(people);
            }
            catch(Exception e)
            {
                var ex = string.Format("Exception in wok logic layer: {0}", e.Message);
                throw new BllException(ex);
            }
            return result;
        }

        public List<ViewPeople> ReadAll()
        {
            List<ViewPeople> lst = null;
            try
            {
                lst=_peoplesDal.ReadAll().Select(ToViewPeople).ToList();
            }
            catch(Exception e)
            {
                var ex = string.Format("Exception in wok logic layer: {0}", e.Message);
                throw new BllException(ex);
            }
            return lst;
        }

        public List<ViewPeople> Filter(int minFacotor, int maxFactor)
        {
            List<ViewPeople> lst = null;
            try
            {
                lst = _peoplesDal.ReadAll().Select(ToViewPeople).Where(t => (t.Factor <= maxFactor && t.Factor >= minFacotor)).ToList();
            }
            catch (Exception e)
            {
                var ex = string.Format("Exception in wok logic layer: {0}", e.Message);
                throw new BllException(ex);
            }
            return lst;
        }

        private static ViewPeople ToViewPeople(PeopleBase people)
        {
            var t = DateTime.Now.ToBinary() - people.BirthDate.ToBinary();
           var date= DateTime.FromBinary(t);
            return new ViewPeople{
                           Id = people.Id,
                           Age = date.Year,
                           Name = people.Name,
                           Factor = Math.Round((people.Weight / Math.Pow(people.Height, 2)), 2)
                       };
        }
    }
}
